package com.zhou.common.mybatis.template.shiro.service;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.zhou.common.mybatis.template.shiro.dto.MyToken;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.UUID;
import java.util.concurrent.ExecutionException;

@Component
public class TestTokenService implements PersistentTokenService, InitializingBean {


    private LoadingCache<String, MyToken> tokenCache;

    @Override
    public MyToken getToken(String tokenId)  {
        try {
            return tokenCache.get(tokenId);
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public MyToken invalidateCacheEntryAndGetToken(String tokenId, boolean invalidateCacheEntry) {
        if (invalidateCacheEntry) {
            tokenCache.invalidate(tokenId);
        }
        return getToken(tokenId);
    }

    @Override
    public void delete(MyToken token) {
        tokenCache.invalidate(token.getId());
    }

    @Override
    public MyToken createToken(String userId) {
        MyToken myToken = new MyToken();
        myToken.setId(UUID.randomUUID().toString().replace("-",""));
        myToken.setValue(UUID.randomUUID().toString().replace("-",""));
        myToken.setUserId(userId);
        myToken.setDate(LocalDateTime.now());
        tokenCache.put(myToken.getId(),myToken);
        return myToken;
    }

    @Override
    public void afterPropertiesSet() {
        tokenCache = CacheBuilder.newBuilder()
                .maximumSize(100)
                .recordStats()
                .build(new CacheLoader<String, MyToken>() {

                    @Override
                    public MyToken load(String s) throws Exception {
                        return null;
                    }
                });
    }
}
